package top.tenebrous.yzl.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

/**
 * @author suxiaolin
 * @date 2019-04-26 13:25
 */
@Slf4j
public class SignUtil {

    public static boolean validation(String appId, String appSecret, JSONObject content, String sfSign) {
        log.info("顺丰验签开始:{}", JSONObject.toJSONString(sfSign));
        String sign = sign(JSON.toJSONString(content));
        log.info("签名:{}", sign);
        return sign.equals(sfSign);
    }

    public static String sign(String content) {
        String md5Result = md5(content.getBytes(StandardCharsets.UTF_8));
        return base64Encode(md5Result.getBytes(StandardCharsets.UTF_8));
    }

    /**
     * 签名方法
     * 参数：content：要发送的JSON结构字符串
     * 返回值：签名信息字符串
     * 注意：签名计算结果可以到此页面进行验证：http://sftc.jsonce.com/sign/
     */
    public static String sign(String appId, String appSecret, String content) {
        String toSign = content + "&" + appId + "&" + appSecret;
        String md5Result = md5(toSign.getBytes(StandardCharsets.UTF_8));
        return base64Encode(md5Result.getBytes(StandardCharsets.UTF_8));
    }

    private static String toHex(byte[] bytes) {
        final char[] hexDigits = "0123456789abcdef".toCharArray();
        StringBuilder ret = new StringBuilder(bytes.length * 2);
        for (byte aByte : bytes) {
            ret.append(hexDigits[(aByte >> 4) & 0x0f]);
            ret.append(hexDigits[aByte & 0x0f]);
        }
        return ret.toString();
    }

    private static String md5(byte[] toSignBytes) {
        try {
            java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
            byte[] bytes = md.digest(toSignBytes);
            return toHex(bytes);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static String base64Encode(byte[] md5ResultBytes) {
        java.util.Base64.Encoder be = java.util.Base64.getEncoder();
        return be.encodeToString(md5ResultBytes);
    }


    public static String generateOpenSign(String postData, Long appId, String appKey) {
        try {
            StringBuilder sb = new StringBuilder();
            sb.append(postData);
            sb.append("&" + appId + "&" + appKey);
            log.info("验签参数为：{}", sb.toString());
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] md5 = md.digest(sb.toString().getBytes("utf-8"));
            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < md5.length; offset++) {
                i = md5[offset];
                if (i < 0) {
                    i += 256;
                }
                if (i < 16) {
                    buf.append("0");
                }
                buf.append(Integer.toHexString(i));
            }
            String ret = Base64.encodeBase64String(buf.toString().getBytes("utf-8"));
            return ret;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static boolean validationSf(Long appId, String appSecret, JSONObject content, String sfSign) {
        log.info("顺丰验签开始:{}", JSONObject.toJSONString(sfSign));
        String sign = generateOpenSign(content.toJSONString(), appId, appSecret);
        log.info("签名:{}", sign);
        return !sign.equals(sfSign);
    }

    public static void main(String[] args) {
        String message = "{\"rider_lng\":116.335075,\"shop_id\":3243279847393,\"operator_name\":\"李建波\",\"order_status\":15,\"operator_phone\":\"18615501228\",\"status_desc\":\"配送员已取货\",\"url_index\":\"rider_status\",\"sf_ucode\":\"01371895\",\"rider_lat\":39.943298,\"shop_order_id\":\"TO202305239534054\",\"push_time\":1684774016,\"sf_order_id\":\"JS4157146257400\"}";
        validationSf(1664311914l, "28c8d95a1ff017dc2efbed49234c7b04", JSONObject.parseObject(message), "NjU2YTNhYmQxMzMzZmFiNzY5ZDYwY2Y0MDIxY2ZlMjY=");
    }
}
